﻿using System;
using System.ServiceModel.DomainServices.Server;

namespace Falafel.Services.Web
{
    public static class FalafelGlobal
    {
        public static IDomainServiceFactory DefaultFactory { get; set; }
        public static void Init()
        {
            DefaultFactory = DomainService.Factory;
            DomainService.Factory = new FalafelDomainServiceFactory();
        }
    }

    public class FalafelDomainServiceFactory : IDomainServiceFactory
    {
        public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
        {
            // if it is one of the 'known services', i.e the built in ones that RIA knows about, then allow the Default Factory to 
            // create them. You will still get 'your' custom services, but let the default factory create them.

            if (domainServiceType == typeof(AuthenticationService) || domainServiceType == typeof(UserRegistrationService))
                return FalafelGlobal.DefaultFactory.CreateDomainService(domainServiceType, context);

            // otherwise, this is one of your domain services, for instance the OrderService. You will be calling a non default constructor
            // that takes a user as a parameter. To get this user, create an Authentication Service instance and call it's GetUser. Then, armed
            // with the user, create your domain service.
            using (AuthenticationService auth = new AuthenticationService())
            {
                auth.Initialize(context);
                User currentUser = auth.GetUser();
                // Call the construcor that takes a user
                DomainService service = (DomainService)Activator.CreateInstance(
                    domainServiceType, 
                    currentUser);
                service.Initialize(context);
                return service;
            }
        }

        public void ReleaseDomainService(DomainService domainService)
        {
            domainService.Dispose();
        }
    }
}